<style>
.page {
  text-align: center;
  margin-top: 7px;
}
.page1 {
  text-align: center;
  margin-top: 15px;
  overflow-x: hidden;
  overflow-y: auto;
  table-layout: fixed;
}
.ivu-table-overflowX {
  overflow-x: hidden;
}
.demo-drawer-profile {
  font-size: 14px;
}
.demo-drawer-profile .ivu-col {
  margin-bottom: 12px;
}
.myrole {
  margin-left: 10px;
}
.in1 {
  margin-left: 7px;
}
</style>
<template>
  <div>
    <Breadcrumb>
      <BreadcrumbItem to="/main/myInfo">
        <e-icon icon-name="el-icon-s-home"></e-icon>主页
      </BreadcrumbItem>
      <BreadcrumbItem>
        <e-icon icon-name="el-icon-setting"></e-icon>系统管理
      </BreadcrumbItem>
      <BreadcrumbItem>用户管理 </BreadcrumbItem>
    </Breadcrumb>

    <Divider />

    <Button type="primary" icon="md-person-add" @click="open">添加用户</Button>

    <Modal
      ref="modal1"
      :loading="isLoading"
      v-model="modal1"
      title="添加用户"
      @on-ok="addUser('userPo')"
      @on-cancel="cancel"
    >
      <Form
        ref="userPo"
        :model="userPo"
        :rules="ruleValidate"
        :label-width="80"
      >
        <FormItem label="用户名称" prop="name">
          <Input
            clearable
            v-model="userPo.name"
            placeholder="请输入用户名称"
          ></Input>
        </FormItem>
        <FormItem label="登录账号" prop="account">
          <Input
            clearable
            v-model="userPo.account"
            placeholder="请输入登录账号"
          ></Input>
        </FormItem>
        <FormItem label="登录密码" prop="password">
          <Input
            clearable
            v-model="userPo.password"
            placeholder="请输入登录密码"
            type="password"
            password
            :value="123456"
          ></Input>
        </FormItem>
        <FormItem label="用户状态" prop="status">
          <i-switch
            true-color="#13ce66"
            false-color="#ff4949"
            size="large"
            :true-value="0"
            :false-value="1"
            v-model="userPo.status"
          >
            <span slot="open">正常√</span>
            <span slot="close">禁用×</span>
          </i-switch>
        </FormItem>
        <FormItem label="用户角色" prop="roleIdList">
          <CheckboxGroup v-model="userPo.roleIdList">
            <Checkbox
              v-for="item in selectRole"
              :label="item.id"
              :value="item.id"
              :key="item.id"
              border
              >{{ item.value }}</Checkbox
            >
          </CheckboxGroup>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      ref="modal2"
      :loading="isLoading"
      v-model="modal2"
      title="修改用户"
      @on-ok="updateUser('userPo2')"
      @on-cancel="cancel"
    >
      <Form
        ref="userPo2"
        :model="userPo"
        :rules="ruleValidate2"
        :label-width="80"
      >
        <FormItem label="用户名称" prop="name">
          <Input
            clearable
            v-model="userPo.name"
            placeholder="请输入用户名称"
          ></Input>
        </FormItem>
        <FormItem label="登录账号" prop="account">
          <Input
            clearable
            v-model="userPo.account"
            placeholder="请输入登录账号"
          ></Input>
        </FormItem>
        <FormItem label="用户状态" prop="status">
          <i-switch
            true-color="#13ce66"
            false-color="#ff4949"
            size="large"
            :true-value="0"
            :false-value="1"
            v-model="userPo.status"
          >
            <span slot="open">正常</span>
            <span slot="close">禁用</span>
          </i-switch>
        </FormItem>
        <FormItem label="用户角色" prop="roleIdList">
          <CheckboxGroup v-model="userPo.roleIdList">
            <Checkbox
              v-for="item in selectRole"
              :label="item.id"
              :value="item.id"
              :key="item.id"
              >{{ item.value }}</Checkbox
            >
          </CheckboxGroup>
        </FormItem>
      </Form>
    </Modal>

    <Input
      class="in1"
      clearable
      v-model="userQo.name"
      placeholder="请输入用户名称"
      style="width: 200px"
    />
    <Input
      class="in1"
      clearable
      v-model="userQo.account"
      placeholder="请输入登录账号"
      style="width: 200px"
    />
    <Select
      class="in1"
      v-model="userQo.status"
      clearable
      style="width: 200px"
      placeholder="请选择用户状态"
    >
      <Option value="0">正常</Option>
      <Option value="1">禁用</Option>
    </Select>
    <!-- <Select placeholder="请选择用户角色" multiple style="width: 260px">
      <Option v-for="item in selectRole" :value="item.value" :key="item.id">{{
        item.value
      }}</Option>
    </Select> -->
    <Button class="in1" type="primary" icon="ios-search" @click="selectUser"
      >搜索</Button
    >
    <Button class="in1" icon="md-close" @click="reset">清除</Button>
    <Table
      style="width: 100%"
      context-menu
      show-context-menu
      class="page1"
      ref="selection"
      border
      :columns="columns1"
      :data="data.records"
      @on-selection-change="checkUser"
      @on-contextmenu="handleContextMenu"
      :loading="loading"
    >
      <template slot="contextMenu">
        <DropdownItem @click.native="handleContextMenuEdit">修改</DropdownItem>
        <DropdownItem
          @click.native="handleContextMenuDelete"
          style="color: #ed4014"
          >删除</DropdownItem
        >
      </template>
    </Table>
    <Button
      class="page1"
      type="error"
      ghost
      @click="ifDeleteAll"
      icon="ios-trash"
      >删除所选</Button
    >
    <Button
      class="page1"
      type="warning"
      ghost
      @click="disabledCheckUser"
      icon="ios-switch"
      >注销/恢复所选</Button
    >
    <Button class="page1" @click="resetCheckPsw" icon="md-refresh"
      >重置所选</Button
    >
    <Page
      class="page"
      :total="data.total"
      :current="data.current"
      :page-size="6"
      :page-size-opts="pagesizeopts"
      @on-change="changePage"
      @on-page-size-change="sizeChange"
      show-elevator
      show-total
      show-sizer
    />
    <Modal v-model="value4" width="450">
      <p slot="header">
        <Icon type="ios-information-circle"></Icon>
        <span>用户详情信息</span>
      </p>
      <div style="text-align: center">
        <Card style="width: 420px">
          <div style="float: left; margin-right: 40px">
            <Avatar
              style="
                color: #f56a00;
                width: 90px;
                height: 90px;
                background-color: #e3f2fd;
                text-algin: center;
                line-height: 90px;
              "
              >{{ this.UserRoleMenuPo.name }}</Avatar
            >
          </div>
          <div style="width: 20px; height: 200px; float: left"></div>
          <div>
            <div style="text-align: left">
              <h4>用户名称：{{ this.UserRoleMenuPo.name }}</h4>
              <h4>用户账号：{{ this.UserRoleMenuPo.account }}</h4>
              <h4>
                用户状态 ：<Tag
                  type="dot"
                  color="success"
                  v-if="this.UserRoleMenuPo.status == 0"
                  >正常</Tag
                >
                <Tag
                  type="dot"
                  color="error"
                  v-if="this.UserRoleMenuPo.status == 1"
                  >禁用</Tag
                >
              </h4>

              <h4 style="text-algin: center">
                用户角色：
                <span
                  v-for="(items, index) in UserRoleMenuPo.sysRoleList"
                  :key="index"
                >
                  <Tag type="dot" color="primary">{{ items.name }}</Tag>
                </span>
              </h4>
            </div>
          </div>
        </Card>
      </div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //表格加载
      loading: true,
      //每页展示条数
      pagesizeopts: [6, 10, 15, 20],
      //存放查询用户userVo的信息
      data: {},
      //数据库角色的集合
      selectRole: [],
      //查询用户的查询条件
      userQo: {
        pageSize: 6,
        pageIndex: 1,
      },
      //添加用户确定按钮的一直加载，添加信息不符合要求时不会关闭弹窗
      isLoading: true,
      //添加用户->是否打开弹窗
      modal1: false,
      //修改用户->是否打开弹窗
      modal2: false,
      //添加用户时存储用户的信息
      userPo: {
        roleIdList: [],
      },
      //存储多选时用户id
      userIdList: [],
      //存储用户的详情信息
      UserRoleMenuPo: {},
      //用户详情页面的style
      pStyle: {
        fontSize: "16px",
        color: "rgba(0,0,0,0.85)",
        lineHeight: "24px",
        display: "block",
        marginBottom: "16px",
      },
      //是否显示用户详情页
      value4: false,
      //右键表格的行数
      contextLine: "",
      //添加用户时的表单验证
      ruleValidate: {
        account: [
          { required: true, message: "登录账号不能为空", trigger: "blur" },
        ],
        password: [
          {
            required: true,
            message: "用户登录密码不能为空",
            trigger: "blur",
          },
        ],
        roleIdList: [
          {
            required: true,
            type: "array",
            min: 1,
            message: "至少选择一个角色",
            trigger: "blur",
          },
        ],
        // status: [
        //   {
        //     required: true,
        //     message: "用户状态不能为空",
        //   },
        // ],
      },
      //修改用户时的表单验证
      ruleValidate2: {
        account: [
          { required: true, message: "登录账号不能qq为空", trigger: "blur" },
        ],
        roleIdList: [
          {
            required: true,
            type: "array",
            min: 1,
            message: "至少选择一个角色",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "用户状态不能为空",
          },
        ],
      },
      //用户的表格
      columns1: [
        {
          width: 60,
          type: "selection",
        },
        {
          title: "ID",
          key: "id",
          width: 60,
        },
        {
          title: "用户名称",
          key: "name",
          width: 200,
        },
        {
          title: "登录账号",
          key: "account",
          width: 180,
        },
        {
          title: "用户角色",
          key: "roleName",
          width: 230,
        },
        {
          title: "用户状态",
          key: "statusShow",
          width: 120,
          align: "center",
          render: (h, params) => {
            const row = params.row;
            return h(
              "i-switch",
              {
                props: {
                  size: "large",
                  trueColor: "#13ce66",
                  falseColor: "#ff4949",
                  value: row.status === 0,
                },
                nativeOn: {
                  click: () => {
                    this.disabledUser(params.index);
                  },
                },
              },
              [
                h("span", { slot: "open" }, "正常"),
                h("span", { slot: "close" }, "禁用"),
              ]
            );
          },
        },
        {
          title: "操作",
          align: "center",
          render: (h, params) => {
            let ifStatus;
            if (params.row.status == 0) {
              ifStatus = true;
            } else if (params.row.status == 1) {
              ifStatus = false;
            }
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    icon: "md-glasses",
                  },
                  style: {
                    id: "btn1",
                    marginLeft: "5px",
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                    },
                  },
                },
                "详情"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "info",
                    size: "small",
                    icon: "md-create",
                  },
                  style: {
                    marginLeft: "5px",
                  },
                  on: {
                    click: () => {
                      this.open2(params.index);
                    },
                  },
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                    icon: "ios-trash-outline",
                  },
                  style: {
                    marginLeft: "5px",
                  },
                  on: {
                    click: () => {
                      this.ifDelete(params.index);
                    },
                  },
                },
                "删除"
              ),
              // ifStatus
              //   ? h(
              //       "Button",
              //       {
              //         props: {
              //           type: "warning",
              //           size: "small",
              //           icon: "ios-switch-outline",
              //         },
              //         style: {
              //           marginLeft: "5px",
              //         },
              //         on: {
              //           click: () => {
              //             this.disabledUser(params.index);
              //           },
              //         },
              //       },
              //       "注销"
              //     )
              //   : h(
              //       "Button",
              //       {
              //         props: {
              //           type: "success",
              //           size: "small",
              //           icon: "ios-switch-outline",
              //         },
              //         style: {
              //           marginLeft: "5px",
              //         },
              //         on: {
              //           click: () => {
              //             this.disabledUser(params.index);
              //           },
              //         },
              //       },
              //       "恢复"
              //     ),
              h(
                "Button",
                {
                  props: {
                    size: "small",
                    icon: "md-refresh",
                  },
                  style: {
                    marginLeft: "5px",
                  },
                  on: {
                    click: () => {
                      this.resetPsw(params.index);
                    },
                  },
                },
                "重置"
              ),
            ]);
          },
        },
      ],
    };
  },
  created() {
    //页面加载时
    //查询用户
    this.selectUser();
    //查询角色
    this.roleList();
  },
  methods: {
    //弹出框点取消时
    cancel() {},
    //查询用户
    selectUser() {
      this.loading = true;
      this.$axios
        .post("/user/userListPages", this.userQo)
        .then((result) => {
          this.data = result.data.data;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取角色列表，以便搜索用户时选择
    roleList() {
      this.$axios
        .get("/role/roleList")
        .then((result) => {
          this.selectRole = result.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //打开添加用户弹窗
    open() {
      this.modal1 = true;
    },
    //打开修改用户弹窗
    open2(index) {
      this.$axios
        .get("/user/selectUserById", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.userPo = {
            roleIdList: [],
          };
          this.userPo.id = result.data.data.id;
          this.userPo.name = result.data.data.name;
          this.userPo.account = result.data.data.account;
          this.userPo.status = result.data.data.status;
          result.data.data.sysRoleList.forEach((element) => {
            this.userPo.roleIdList.push(element.id);
          });
          this.modal2 = true;
          console.log(this.userPo.roleIdList);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //添加用户
    addUser(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的用户信息是否正确
        if (valid) {
          this.$axios
            .post("/user/addUser", this.userPo)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: "添加成功",
                });
                //插入数据成功更新查询
                this.selectUser();
                //清空上次保存的user信息
                this.userPo = {
                  roleIdList: [],
                };
                this.modal1 = false;
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "添加失败",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //改变页数时
    changePage(e) {
      //变更查询时的页数条件
      this.userQo.pageIndex = e;
      this.selectUser();
    },
    //多选选中用户
    checkUser(e) {
      //先将选中id设为空，以免重复添加id
      this.userIdList = [];
      console.log(e);
      //循环添加id
      e.forEach((element) => {
        this.userIdList.push(element.id);
      });
      console.log(this.userIdList);
    },

    //弹框问是否删除多选
    ifDeleteAll() {
      if (
        this.userIdList !== undefined &&
        this.userIdList !== null &&
        this.userIdList.length > 0
      ) {
        this.$Modal.confirm({
          title: "警告",
          content: "<p>你真的要删除这些用户么?</p>",
          onOk: () => {
            this.deleteCheckUser();
          },
          onCancel: () => {},
        });
      } else {
        this.$Message.warning({
          top: 30,
          duration: 2.5,
          background: true,
          content: "您未选择任何用户",
        });
      }
    },
    //删除选中的用户
    deleteCheckUser() {
      this.$axios
        .post("/user/deleteCheckUser", this.userIdList)
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectUser();
            this.userIdList = [];
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //弹框问是否删除
    ifDelete(index) {
      this.$Modal.confirm({
        title: "警告",
        content: "<p>你真的要删除该用户么?</p>",
        onOk: () => {
          this.remove(index);
        },
        onCancel: () => {},
      });
    },
    //删除单个用户
    remove(index) {
      this.$axios
        .get("/user/deleteUser", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectUser();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //重置单个用户密码
    resetPsw(index) {
      this.$axios
        .get("/user/resetPsw", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              duration: 2.5,
              background: true,
              content: "重置成功",
            });
            //重置成功，更新查询
            this.selectUser();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "重置失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //重置选中用户密码
    resetCheckPsw() {
      if (
        this.userIdList !== undefined &&
        this.userIdList !== null &&
        this.userIdList.length > 0
      ) {
        this.$axios
          .post("/user/resetCheckPsw", this.userIdList)
          .then((result) => {
            if (result.data.code == 0) {
              this.$Message.success({
                top: 30,
                duration: 2.5,
                background: true,
                content: "重置成功",
              });
              //重置成功，更新查询
              this.selectUser();
              this.userIdList = [];
            } else {
              this.$Message.error({
                top: 30,
                duration: 2.5,
                background: true,
                content: "重置失败",
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$Message.warning({
          top: 30,
          duration: 2.5,
          background: true,
          content: "您未选择任何用户",
        });
      }
    },
    //注销/恢复选中用户
    disabledCheckUser() {
      if (
        this.userIdList !== undefined &&
        this.userIdList !== null &&
        this.userIdList.length > 0
      ) {
        this.$axios
          .post("/user/disabledCheckUser", this.userIdList)
          .then((result) => {
            if (result.data.code == 0) {
              this.$Message.success({
                top: 30,
                duration: 2.5,
                background: true,
                content: "操作成功",
              });
              //删除成功，更新查询
              this.selectUser();
              this.userIdList = [];
            } else {
              this.$Message.error({
                top: 30,
                duration: 2.5,
                background: true,
                content: "操作失败",
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$Message.warning({
          top: 30,
          duration: 2.5,
          background: true,
          content: "您未选择任何用户",
        });
      }
    }, //注销/恢复单个用户
    disabledUser(index) {
      this.$axios
        .get("/user/disabledUser", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              top: 30,
              duration: 2.5,
              background: true,
              content: "操作成功",
            });
            //删除成功，更新查询
            this.selectUser();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "操作失败",
            });
          }
        })
        .catch((err) => {
          get;
          console.log(err);
        });
    },
    //用户详情信息
    show(index) {
      this.value4 = true;
      this.$axios
        .get("/user/selectUserById", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.UserRoleMenuPo = result.data.data;
          console.log(this.UserRoleMenuPo);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //修改用户信息
    updateUser(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的用户信息是否正确
        if (valid) {
          console.log(this.userPo.roleIdList);
          this.$axios
            .post("/user/updateUser", this.userPo)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: "修改成功",
                });
                //插入数据成功更新查询
                this.selectUser();
                //清空上次保存的user信息
                this.userPo = {
                  roleIdList: [],
                };
                this.modal2 = false;
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "修改失败",
                });
              }
              console.log(result.data);
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //关闭弹窗时，清除userPo信息
    cancel() {
      this.userPo = {
        roleIdList: [],
      };
    },
    //右键表格时得到右键表格的位置
    handleContextMenu(row) {
      const index = this.data.records.findIndex(
        (item) => item.name === row.name
      );
      this.contextLine = index;
    },
    //右键修改信息
    handleContextMenuEdit() {
      this.open2(this.contextLine);
    },
    //右键删除用户
    handleContextMenuDelete() {
      this.$Modal.confirm({
        title: "警告",
        content: "<p>你真的要删除该用户么?</p>",
        onOk: () => {
          this.remove(this.contextLine);
        },
        onCancel: () => {},
      });
    },
    //改变页面显示数据大小后
    sizeChange(e) {
      this.userQo.pageSize = e;
      this.selectUser();
    },
    //清除查询条件
    reset() {
      (this.userQo = {
        pageSize: this.userQo.pageSize,
        pageIndex: 1,
      }),
        this.selectUser();
    },
  },
};
</script>